package com.key.win.business.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.exception.BizException;
import com.key.win.base.page.MybatisPageServiceTemplate;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.business.chat.dao.ImGroupDao;
import com.key.win.business.chat.model.ImGroup;
import com.key.win.business.chat.model.ImGroupNotice;
import com.key.win.business.chat.model.ImGroupUser;
import com.key.win.business.chat.service.ImGroupNoticeService;
import com.key.win.business.chat.service.ImGroupService;
import com.key.win.business.chat.service.ImGroupUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

@Service
public class ImGroupServiceImpl extends ServiceImpl<ImGroupDao, ImGroup> implements ImGroupService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ImGroupUserService imGroupUserService;

    @Autowired
    private ImGroupNoticeService imGroupNoticeService;

    public PageResult<ImGroup> findGroupByPaged(PageRequest<ImGroup> t) {
        MybatisPageServiceTemplate<ImGroup, ImGroup> query = new MybatisPageServiceTemplate<ImGroup, ImGroup>(this.baseMapper) {
            @Override
            protected AbstractWrapper constructWrapper(ImGroup group) {
                return buildWrapper(group);
            }
        };
        return query.doPagingQuery(t);
    }

    private AbstractWrapper buildWrapper(ImGroup imGroup) {
        if (imGroup == null) {
            logger.error("group is null!");
            throw new IllegalArgumentException("好友为空！");
        }
//        if (StringUtils.isBlank(imGroup.getUserId())) {
//            logger.error("userId is null!");
//            throw new IllegalArgumentException("当前用户为空！");
//        }
        LambdaQueryWrapper<ImGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(imGroup.getName())) {
            lambdaQueryWrapper.like(ImGroup::getName, imGroup.getName());
        }
        if (StringUtils.isNotBlank(imGroup.getIntroduce())) {
            lambdaQueryWrapper.like(ImGroup::getIntroduce, imGroup.getIntroduce());
        }
        if (StringUtils.isNotBlank(imGroup.getNotice())) {
            lambdaQueryWrapper.like(ImGroup::getNotice, imGroup.getIntroduce());
        }
        // lambdaQueryWrapper.eq(ImGroup::getUserId, imGroup.getUserId());
        if (imGroup.getType() != null) {
            lambdaQueryWrapper.eq(ImGroup::getType, imGroup.getType());
        }
        if (imGroup.getStatus() != null) {
            lambdaQueryWrapper.eq(ImGroup::getStatus, imGroup.getStatus());
        }
        return lambdaQueryWrapper;
    }

    public List<ImGroup> findGroup(ImGroup imGroup) {
        return this.list(this.buildWrapper(imGroup));
    }

    public boolean addGroup(ImGroup imGroup) {
        if (imGroup == null) {
            logger.error("group is null!");
            throw new IllegalArgumentException("组为空！");
        }
        if (StringUtils.isBlank(imGroup.getName())) {
            logger.error("groupId is null!");
            throw new IllegalArgumentException("组名称为空！");
        }
        if (StringUtils.isBlank(imGroup.getUserId())) {
            logger.error("userId is null!");
            throw new IllegalArgumentException("当前用户为空！");
        }
        ImGroup iGroup = new ImGroup();
        iGroup.setName(imGroup.getName());
        iGroup.setUserId(imGroup.getUserId());
        List<ImGroup> imGroups = this.findGroup(iGroup);
        if (!CollectionUtils.isEmpty(imGroups)) {
            logger.error("组[{}]已是创建过了", imGroup.getName());
            throw new BizException(imGroup.getName() + "组已经存在！");
        }
        imGroup.setNoticeId(addImGroupNotice(imGroup));
        if (this.save(imGroup)) {
            ImGroupUser imGroupUser = new ImGroupUser();
            imGroupUser.setGroupId(imGroup.getId());
            imGroupUser.setUserId(AuthenticationUtil.getUserId());
            return imGroupUserService.addGroupUser(imGroupUser);
        }
        return Boolean.FALSE;
    }

    @Override
    public boolean updateGroup(ImGroup imGroup) {
        if (imGroup == null) {
            logger.error("group is null!");
            throw new IllegalArgumentException("组友为空！");
        }
        if (StringUtils.isBlank(imGroup.getId())) {
            logger.error("group Id is null!");
            throw new IllegalArgumentException("组友为空！");
        }
        ImGroup dbImGroup = this.getById(imGroup.getId());
        if (dbImGroup == null) {
            logger.error("没有找到id[]的组信息！", imGroup.getId());
            throw new IllegalArgumentException("组不存在！");
        }
        if (StringUtils.isNotBlank(imGroup.getName())) {
            dbImGroup.setName(imGroup.getName());
        }
        if (StringUtils.isNotBlank(imGroup.getNotice())) {
            if (!imGroup.getNotice().equals(dbImGroup.getNotice())) {
                dbImGroup.setNoticeId(addImGroupNotice(imGroup));
            }
            dbImGroup.setNotice(imGroup.getNotice());
        }
        if (StringUtils.isNotBlank(imGroup.getIntroduce())) {
            dbImGroup.setIntroduce(imGroup.getIntroduce());
        }
        if (StringUtils.isNotBlank(imGroup.getIcon())) {
            dbImGroup.setIcon(imGroup.getIcon());
        }
        if (imGroup.getType() != null) {
            dbImGroup.setType(imGroup.getType());
        }
        if (imGroup.getStatus() != null) {
            dbImGroup.setStatus(imGroup.getStatus());
        }
        return this.saveOrUpdate(dbImGroup);
    }

    public boolean clearNotice(String groupId) {
        ImGroup dbImGroup = this.getById(groupId);
        if (dbImGroup == null) {
            logger.error("没有找到id[]的组信息！", groupId);
            throw new IllegalArgumentException("组不存在！");
        }
        dbImGroup.setNoticeId(null);
        dbImGroup.setNotice(null);
        return this.saveOrUpdate(dbImGroup);
    }

    private String addImGroupNotice(ImGroup imGroup) {
        ImGroupNotice imGroupNotice = new ImGroupNotice();
        imGroupNotice.setNotice(imGroup.getNotice());
        if (imGroupNoticeService.saveOrUpdateImGroupNotice(imGroupNotice)) {
            return imGroupNotice.getId();
        }
        logger.error("公告保存失败:{0}", imGroup.getName());
        throw new BizException("公告保存失败！");
    }

    public List<ImGroup> findGroupByUserId(String userId) {
        return this.baseMapper.findMyGroup(userId);
    }

    @Override
    public List<ImGroup> findGroupByUserIds(Set<String> userIds) {
        return this.baseMapper.findMyGroup(userIds);
    }

    @Override
    public boolean deleteGroup(String id) {
        if (imGroupUserService.deleteGrouUserByGroupId(id) >= 0) {
            return this.removeById(id);
        }
        return false;
    }
}
